import 'dart:io';

import 'package:erp/Entity/ProductType.dart';
import 'package:erp/UI/Components/ImageSelector.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:flutter/services.dart';

Future<bool> showProductTypeEditDialog(BuildContext context, ProductType type, {DialogOpenMode mode = DialogOpenMode.ADD}) async {
  _Parameter param = _Parameter(
    productType: type,
    imageResult: SelectResult(
      imageUrl: type?.imgurl,
    )
  );

  return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("تاۋار تۈرى ئىسمىنى كىرگۈزۈڭ"),
          content: _ProductTypeEditDialogStateful(param),
          actions: <Widget>[
            FlatButton(
                onPressed: () async {
                  if (mode == DialogOpenMode.ADD || param.imageResult.selected)
                    param.productType.imgurl = await param.imageResult.getBase64String();
                  Navigator.of(context).pop(true);
                },
                child: Text("جەزىملەشتۈرۈش"))
          ],
        );
      }
  );
}

class _ProductTypeEditDialogStateful extends StatefulWidget {
  _Parameter param;

  _ProductTypeEditDialogStateful(this.param);

  @override
  State<StatefulWidget> createState() => _ProductTypeEditDialogState(param);
}

class _ProductTypeEditDialogState extends State<_ProductTypeEditDialogStateful> {
  TextEditingController _nameController;
  _Parameter param;

  _ProductTypeEditDialogState(this.param);

  @override
  void initState() {
    _nameController = TextEditingController(text: param.productType.name);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200.0,
      height: 290.0,
      child: Column(
        children: <Widget>[
          TextField(
            decoration: InputDecoration(
              hintText: "تاۋار تۈرى ئىسمى",
              labelText: "تاۋار تۈرى ئىسمى",
            ),
            onChanged: (value) {
              param.productType.name = value;
            },
            controller: _nameController,
          ),
          SizedBox(height: 10.0,),
          ImageSelector(param.imageResult),
          SizedBox(height: 10.0,),
        ],
      ),
    );
  }
}

class _Parameter {
  ProductType productType;
  SelectResult imageResult;

  _Parameter({this.productType, this.imageResult});
}
enum DialogOpenMode{
  ADD, EDIT
}